﻿var tempFileBase64 = null;
var tempFileName = null;
var fileTempRunningNumber = 1;

function readFile(input) {
    var f1;
    if (input.files && (f1 = input.files[0])) {
        var FR = new FileReader();
        tempFileName = f1.name;
        var url = '/Complaint/InformAttachment?file_name=' + tempFileName;

        FR.onload = function (e) {
            tempFileBase64 = e.target.result;

            $.colorbox({
                iframe: true,
                width: "550px",
                height: "500px",
                fastIframe: false,
                onOpen: function () { blockAction = 'obj'; returntext = ''; },
                onClosed: function() {
                    if (returntext != '') {
                        $("#block_" + blockAction).find("input").remove();
                        $("#block_" + blockAction).find("div").remove();
                        $("#block_" + blockAction).append('<input type="hidden" name="' + blockAction + '" value="' + returnvalue + '" /><div class="blockReAction" data-value="' + returnvalue + '">' + returntext + '<span onclick="removebox(\'' + blockAction + '\',' + returnvalue + ');"></span></div>');

                    }
                },
                href: url
            });

            $('#case_attachment_input').val('');
        };
        FR.readAsDataURL(f1);
    }
}

$("#case_attachment_input").change(function () {
    readFile(this);
});

function makeHidden(name, value) {
    return "<input type=\"hidden\" name=\"" + name + "\" id=\"" + name + "\" value=\"" + value + '" />';
}

function removeBox1(id) {
    $('#' + id).remove();
}

function addFile(file_description, doc_type_id, doc_no, doc_date, doc_ref_no, doc_ref_date, file_name, doc_type) {
    var runId = 'file_new_attach_' + (fileTempRunningNumber++);

    var strHtml = '';
    strHtml += makeHidden("file_content", tempFileBase64);
    strHtml += makeHidden("file_description", file_description);
    strHtml += makeHidden("doc_type_id", doc_type_id);
    strHtml += makeHidden("doc_no", doc_no);
    strHtml += makeHidden("doc_date", doc_date);
    strHtml += makeHidden("doc_ref_no", doc_ref_no);
    strHtml += makeHidden("doc_ref_date", doc_ref_date);
    strHtml += makeHidden("file_name", file_name);
    strHtml += makeHidden("doc_type", doc_type);
    strHtml += '<div class="blockReAction" id="' + runId + '">' + tempFileName +
        (doc_type == 'I' ? 'รับเข้า' : (doc_type == 'O' ? 'ส่งออก' : 'อื่นๆ')) +
        '<span onclick="removeBox1(\'' + runId + '\');"></span></div>';

    $('#block_case_attachments').append(strHtml);
    $.colorbox.close();
    $("#case_attachment_input").val('');
} 